

import java.util.Random;

import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.Instance;
import weka.core.Instances;

public class ClassifierBuilder {
	
	Classifier mClassifier;
	Instances trainingSet = null;
	
	public ClassifierBuilder(Classifier algo) {
//		AttributeSelectedClassifier classifier = new AttributeSelectedClassifier();
//		CfsSubsetEval eval = new CfsSubsetEval();
//		GreedyStepwise search = new GreedyStepwise();
//		search.setSearchBackwards(true);
//		classifier.setClassifier(algo); // Choose classifer algo
//		classifier.setEvaluator(eval);
//		classifier.setSearch(search);
		// ---------------------
		// For any reason this wont work on Android - so simply use the algo as classifier
		 mClassifier = algo;
		// ---------------------
//		mClassifier = classifier;
	}
	
	public ClassifierBuilder build(Instances training) throws Exception {
		trainingSet = training;
		mClassifier.buildClassifier(trainingSet);
		return this;
	}
	
	public double[] getLikelihood(Instance observation) throws Exception {
		if (trainingSet == null) 
			throw new Exception("Training set not defined");
		else {
			observation.setDataset(trainingSet);
			return mClassifier.distributionForInstance(observation);
		}
	}
	
	public String classify(Instance observation) throws Exception {
		if (trainingSet == null) 
			throw new Exception("Training set not defined");
		else {
			observation.setDataset(trainingSet);
			return ToolBox.CLASSES[(int) mClassifier.classifyInstance(observation)];
		}
	}
	
	// EVALUATION
	// Only on DESKTOP MACHINE
	// Evaluate the classifier with it's trainingset
	// with a 10-fold cross validation technique
	public Evaluation evaluate() throws Exception {
		if (trainingSet == null) 
			throw new Exception("Training set not defined");
		else {
			Evaluation eval = new Evaluation(trainingSet);
			eval.crossValidateModel(mClassifier, trainingSet, 10, new Random(1));
			return eval;
		}	
	}
}